const GoodsCard = new buildPage({
    // 动态调组件 props 需写入 当前父节点
    name: 'GoodsCard',
    template: `
        <div props-list="card.list">
            <div i-for="goods in list">
                <div class="layui-card" style="width: 45%; display: inline-block; margin: 10px">
                  <div class="layui-card-body">
                    <div class="goods_cover">
                        <img :src="/cms/api/community/tool/get_file/{{ goods.goods_cover }}" alt="商品图片">
                    </div>
                    <div class="goods_detail">
                        <span class="goods_detail_title">{{ goods.goods_name }}</span>
                        <p>{{ goods.goods_keyword }}</p>
                        <p>
                            <span style="color: rgb(251, 114, 153);">￥ {{ goods.goods_price_selling }}</span>
                            <span style="float: right">{{ goods.create_time }}</span>
                        </p>
                    </div>
                  </div>
                </div>
            </div>
        </div>
    `,
    data: {}
})

const Video = new buildPage({
    name: 'Video',
    template: `
        <div>
            <div i-for="list in card.list">
                <div>{{ list.goods_name }}</div>
            </div>
        </div>
    `,
    data: {}
})

const TemplateInfo = new buildPage({
    name: 'TemplateInfo',
    template: `
        <div>
            <div i-for="list in card.list">
                <div>{{ list.goods_name }}</div>
            </div>
        </div>
    `,
    data: {}
})

const contentInfo = new buildPage({
    template: `
        <div style="margin-top: 20px" i-for="card in cardList">
            <div class="layui-card">
              <div class="layui-card-header">
                <i :class="layui-icon {{ card.icon }}"></i>
                <span> {{ card.title }}</span>
              </div>
              <div class="layui-card-body">
                <card.component></card.component>
                <p style="text-align: center; padding: 20px;" i-if="!card.list">暂无数据</p>
              </div>
            </div>
        </div>
    `,
    data: {
        cardList: [{
            title: '我的专栏',
            icon: 'layui-icon-template-1',
            component: 'TemplateInfo',
            list: []
        }, {
            title: '我的视频',
            icon: 'layui-icon-video',
            component: 'Video',
            list: []
        }, {
            title: '购物车',
            icon: 'layui-icon-cart',
            component: 'GoodsCard',
            list: [{
                goods_id: 1,
                uid: 1,
                goods_suk_id: '123-123-123',
                number: 12,
                create_time: '2021-06-03',
                update_time: '2021-06-03',
                goods_name: '测试商品',
                goods_cover: '6a0e8d9a-4efb-112e-8754-d64cb11fdb08',
                goods_keyword: '2333',
                goods_price_selling: 999,
                goods_price_market: 1800
            }, {
                goods_id: 1,
                uid: 1,
                goods_suk_id: '123-123-123',
                number: 12,
                create_time: '2021-06-03',
                update_time: '2021-06-03',
                goods_name: '测试商品',
                goods_keyword: '2333',
                goods_cover: '54ef38e9-5535-1821-9c22-dca00e479500',
                goods_price_selling: 999,
                goods_price_market: 1800,
            }]
        }]
    },
    created() {
    }
})

const rightInfo = new buildPage({
    template: `
        <div style="margin-top: 20px">
            <div class="layui-card">
              <div class="layui-card-header">
                <span>
                    <i class="layui-icon layui-icon-username"></i> 
                    <span> 个人信息</span>
                    <p style="float: right; font-size: 12px;cursor: pointer" @click="changeUserInfo">
                        <i class="layui-icon layui-icon-edit"></i>
                        <span> 编辑</span>
                    </p>
                </span>
              </div>
              <div class="layui-card-body">
                  <div style="font-size: 12px; width: 55%; display: inline-block;">
                    <span class="layui-badge layui-bg-orange" style="font-size: 12px;">UID</span>
                    <span style="padding: 0 7px; height: 20px; line-height: 18px; top: 15px;">{{ userinfo.uid }}</span>
                  </div>
                  <div style="font-size: 12px; display: inline-block;">
                    <i class="layui-icon layui-icon-auz" style="font-size: 12px;"></i>
                    <span style="padding: 0 7px; height: 20px; line-height: 18px; position: absolute; top: 15px;">
                        普通用户
                    </span>
                  </div>
              </div>
            </div>
        </div>
    `,
    data: {},
    methods: {
        changeUserInfo() {
            let self = this
            layer.open({
                title: '编辑个人信息',
                content: `
                    <div style="width: 320px" id="changeForm">
                        <input
                            type="text"
                            required
                            value="${self.props.userinfo.nick_name}"
                            lay-verify="required"
                            placeholder="昵称"
                            autocomplete="off"
                            class="layui-input"
                        />
                        <input
                            type="text"
                            required
                            value="${self.props.userinfo.signature}"
                            lay-verify="required"
                            placeholder="签名"
                            autocomplete="off"
                            class="layui-input"
                            style="margin-top: 20px"
                        />
                    </div>
                `
                ,resize: false
                ,yes: function(index, layero){
                    let dom = $('#changeForm > input')
                    let obj = {
                        nick_name: dom[0].value,
                        signature: dom[1].value
                    }

                    // 更新用户信息
                    upUserInfo(obj).then(res => {
                        layer.msg(res.msg)
                        if (res.code === 200) {
                            obj = Object.assign(self.props.userinfo, obj)
                            Reflect.set(self.props, 'userinfo', obj)
                            self.emit('changeUserInfoEmit', obj)
                            layer.close(index)
                        }
                    })
                }
            })
        }
    }
})

// 全部组件数据
const components = {
    contentInfo,
    rightInfo,
    GoodsCard,
    Video,
    TemplateInfo
}

const Home = new buildPage({
    dom: '#home',
    data: {
        userInfo: {},
        tabs: [{
            icon: 'layui-icon-home',
            title: '首页',
            classes: 'layui-this',
            event: 'home'
        }, {
            icon: 'layui-icon-cart',
            title: '我的店铺',
            classes: '',
            event: 'shopAdmin'
        }]
    },
    created() {
        this.StateX.getAction('getUserInfo', 'userInfo').then(info => {
            if (info.uid === undefined) {
                layer.msg('暂未登录')
                window.location.href = `${window.location.origin}/cms/home/cms-pages`
                return
            }
            Reflect.set(this.data, 'userInfo', info)
        })
    },
    components,
    methods: {
        // 更新头像
        changeAvatar(e) {
            let canvas = document.createElement('canvas')
            let context = canvas.getContext('2d')
            let self = this

            layer.open({
                title: '裁剪图片',
                content: `
                    <div style="width: 560px">
                        <img id="userAvatar" style="width: 220px; height: 220px" />
                        <div style="margin: 20px">
                            <span>预览：</span>
                            <img style="width: 120px; height: 120px" id="userAvatarView">
                        </div>
                    </div>
                `
                ,resize: false
                ,success: function () {
                    let reader = new FileReader()
                    reader.readAsDataURL(e.files[0])
                    reader.onload = function(e) {
                        $("#userAvatar").attr("src", this.result).show();
                        let cropper = new Cropper($("#userAvatar")[0], {
                            viewMode: 3,
                            dragMode: 'move',
                            aspectRatio: 1,
                            crop: function (e) {
                                let sourceCanvas = cropper.getCroppedCanvas()
                                let width = sourceCanvas.width;
                                let height = sourceCanvas.height;
                                canvas.width = width;
                                canvas.height = height;
                                context.imageSmoothingEnabled = true;
                                context.drawImage(sourceCanvas, 0, 0, width, height);
                                context.globalCompositeOperation = 'destination-in';
                                context.beginPath();
                                // context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true);
                                context.fill();
                                $('#userAvatarView').attr('src', canvas.toDataURL("image/png"))
                                return canvas;
                            }
                        })
                    };
                }
                ,yes: function(index, layero){
                    let file = base64ToFile($('#userAvatarView').attr('src'))
                    if (file === null) {
                        layer.msg('上传图像失败')
                        return
                    }
                    saveFile({
                        file: file
                    }).then(res => {
                        upUserInfo({
                            avatar: res.items[0].resources_id
                        }).then(res => {
                            layer.msg(res.msg)
                            layer.close(index)
                            Reflect.set(self.data.userInfo, 'avatar', `/cms/api/community/tool/get_file/${res.items[0].resources_id}`)
                        })
                    })
                }
            })
        },
        changePage(event) {
            if (event === 'shopAdmin') {
                // 商户中台地址
                window.open(`https://cmerchant.mzshe.cn/?ak=${Cookies.get('authorization')}`)
            }
        },
        changeUserInfoEmit(data) {
            Reflect.set(this.data, 'userInfo', data)
        }
    }
}).use({
    stateX
}).mount()